import {defineConfig, loadEnv, UserConfig} from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import tailwindcss from '@tailwindcss/vite';

// https://vite.dev/config/
export default ({mode = ''}: UserConfig) =>
  defineConfig({
    base: loadEnv(mode, process.cwd()).VITE_APP_PUBLIC_PATH,
    server: {
      host: '0.0.0.0',
      proxy: {
        '/app/api/': {
          target: loadEnv(mode, process.cwd()).VITE_APP_PROXY,
          changeOrigin: true,
          rewrite: path =>
            mode != 'development' ? path.replace(/^\/app\/api/, '') : path,
          // rewrite: path => path.replace(/^\/api/, ''),
        },
      },
    },
    plugins: [react(), tailwindcss()],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
    build: {
      assetsInlineLimit: 0, // 小于4k的图片不被转成base64 https://cn.vitejs.dev/config/#build-assetsinlinelimit
      chunkSizeWarningLimit: 1000, // 块大小警告的限制（以 kbs 为单位）。 fix: Some chunks are larger than 500 KiB after minification. Consider
      target: 'es2020',
      terserOptions: {
        compress: {
          drop_console: true, // 生产环境移除console
          drop_debugger: true, // 移除debugger
        },
      },
      outDir: loadEnv(mode, process.cwd()).VITE_APP_OUTPUT_DIR, // 静态文件输出目录https://vitejs.cn/config/#build-outdir
      rollupOptions: {
        output: {
          entryFileNames: 'scripts/[name].[hash].js',
          chunkFileNames: 'scripts/[name].[hash].js',
          assetFileNames: ({name = ''}) => {
            if (/.js$/gi.test(name)) {
              return 'scripts/[name].[hash].[ext]';
            }
            if (/.css$/gi.test(name)) {
              return 'styles/[name].[hash].[ext]';
            }
            // 音频文件
            if (/(.mp3|.wav)$/gi.test(name)) {
              return 'assets/audio/[name].[ext]';
            }
            // 视频文件
            if (/(.mp4|.webm)$/gi.test(name)) {
              return 'assets/video/[name].[ext]';
            }
            // 图片或者其他素材，不加hash值
            return 'assets/images' + name?.split('/images')[1];
          },
        },
      },
    },
  });
